package cn.com.easy.permission.web.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.easy.permission.dao.UserDao;
import cn.com.easy.permission.dao.UserLoginRecordDao;
import cn.com.easy.permission.model.UserLoginRecordModel;
import cn.com.easy.permission.model.UserModel;
import cn.com.easy.utils.IPUtils;
import cn.com.easy.utils.RequestUtils;
import cn.com.easy.utils.SecurityUtils;

/**
 * 用户登录登出控制
 * 
 * @author nibili 2014-12-17
 */
@Controller
@RequestMapping("/manage")
public class SystemLoginController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(SystemLoginController.class);

	/** 用户信息dao */
	@Autowired
	private UserDao userDao;
	/** 登录记录 */
	@Autowired
	private UserLoginRecordDao userLoginRecordDao;

	/**
	 * 直接跳到登录页
	 * 
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String index() {
		return "redirect:/manage/login";
	}

	/**
	 * 登录页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response) {
		if (RequestUtils.getCurrentUser(request) != null) {
			return "redirect:/manage/index";
		} else {
			return "/system/system_login/system_login";
		}
	}

	/**
	 * 登录验证
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/login/logincheck", method = RequestMethod.POST)
	public String loginCheck(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) throws Exception {
		// 获取用户名
		String username = request.getParameter("username");
		String sign = request.getParameter("sign");
		String j_captcha = request.getParameter("j_captcha");
		if (RequestUtils.validCaptcha(request, j_captcha) == false) {
			// 检验验证码
			redirectAttributes.addFlashAttribute("loginError", "验证码错误");
			return "redirect:/manage/login";
		} else if (StringUtils.isBlank(username) == true || StringUtils.isBlank(sign) == true) {
			// 用户名或者密码为空
			redirectAttributes.addFlashAttribute("loginError", "用户名或者密码不能为空!");
			return "redirect:/manage/login";
		} else {
			//
			UserModel userModel = userDao.findByLoginname(username);
			// 先验签
			if (userModel == null) {
				// 找不到登录名或者密码错
				redirectAttributes.addFlashAttribute("loginError", "用户名或者密码错误!");
				return "redirect:/manage/login";
			} else {
				// 要签名的字符串
				String toSignString = username + "-" + userModel.getPassword() + "-" + j_captcha + "-" + request.getSession().getId();
				// 私钥
				// String privateKey =
				// "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIHJR7YwqHxuAfywpB69whKBP7Wuegslj5iipZ/HQR8m7rb17/LKHWdXMAN0K10LSn+trrZN3A1tzqfm0gRN7eVb76OHK4YYdfblb2yAq+CyXDbpm30Tg1KjDY4k0SzailQ7bjgbqC/Kw/5NYwYpudlzTfpIEh6+pfHSai0l8+v5AgMBAAECgYAySHhnJtzwMHLGou1DF8PMBZVYX3vbO7cxrLo8eCdL2XqdGhXX2+SeeBIbFHQEfW5knzbUXMAH1+Y7+NqfXk3vg3DDXywBdcOx52Q9Wo59BSutFWSLNwfjyyrvkzxxfRPv80EgSjTbsW6fodeNksh1Ie/lp5KvWSgPkZZK8frAXQJBAM3UhJyemO8kzjy1cy6Pd57F0pfYA/5+DKyfC3J88R6ZNMvO1mLpO3CR3WUlV3WfKqLZlLoDXgU7VvQ1kIkLEhsCQQCha72nHb4Mj4qbnjW0rWDSkdeZkD+q6cz+lLcKz6yCd+m3LQ2KhFtrvvUnxIoNCj1NuiPiUnn9BjfX0yaYwjt7AkAxC3KN3zyRvzNlQ9cuQQE/0+NaSx6ohWB/wWX44cySfe8WoTJ0Xx7Ks/cNIti0Ljj6lN3bdPHyTTFq/1hxTzIBAkADIMleEa97ItT2ywwTYkC8E+NvsGHrd/hm/o7FgNzA8n3u9MqMYqA66Epr6N0b/5TMiszjN+HxS0uNvSPEVg89AkA5xzkgAUa+WloFzs5vS86gvUKPgPreD0tUronOdITQh/i/w8ebSTNLhiICRJkIxB9HmUsT2EPfYC2F0c+OpU/c";
				// 公钥
				// String publicKey =
				// "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCByUe2MKh8bgH8sKQevcISgT+1rnoLJY+YoqWfx0EfJu629e/yyh1nVzADdCtdC0p/ra62TdwNbc6n5tIETe3lW++jhyuGGHX25W9sgKvgslw26Zt9E4NSow2OJNEs2opUO244G6gvysP+TWMGKbnZc036SBIevqXx0motJfPr+QIDAQAB";
				//
				String verifyResult = SecurityUtils.SHA256Normal(SecurityUtils.SHA256Normal(toSignString));
				if (StringUtils.equals(verifyResult, sign) == false) {
					redirectAttributes.addFlashAttribute("loginError", "签名验证失败");
					return "redirect:/manage/login";
				}
				// 账户是否被启用
				if (userModel.isEnable() == true) {
					{ // 最后登录时间
						userModel.setLastLoginTime(new Date());
						// 最后登录ip
						userModel.setLoginIp(IPUtils.getRealIP(request));
						userModel = userDao.save(userModel);
						// 记录，登录日志
						UserLoginRecordModel userLoginRecordModel = new UserLoginRecordModel();
						userLoginRecordModel.setLoginName(userModel.getLoginname());
						userLoginRecordModel.setRealName(userModel.getRealname());
						userLoginRecordModel.setUserId(userModel.getId());
						userLoginRecordModel.setClientIp(userModel.getLoginIp());
						userLoginRecordDao.save(userLoginRecordModel);
					}
					// 用户信息
					RequestUtils.setCurrentUser(request, userModel);
					// 登录日志
					logger.info("用户登录:" + ((UserModel) RequestUtils.getCurrentUser(request)).getId());
					// 验证通过
					return "redirect:/manage/index";
				} else {
					redirectAttributes.addFlashAttribute("loginError", "账号状态异常!");
					return "redirect:/manage/login";
				}
			}
		}
	}

	/**
	 * 退出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		if (session != null) {
			UserModel userModel = (UserModel) RequestUtils.getCurrentUser(request);
			if (userModel != null) {
				// 记录操作日志
				// 记录，登录日志
				UserLoginRecordModel userLoginRecordModel = new UserLoginRecordModel();
				userLoginRecordModel.setLoginName(userModel.getLoginname());
				userLoginRecordModel.setRealName(userModel.getRealname());
				userLoginRecordModel.setUserId(userModel.getId());
				userLoginRecordModel.setClientIp(IPUtils.getRealIP(request));
				userLoginRecordModel.setLogin(false);
				userLoginRecordDao.save(userLoginRecordModel);
				logger.info("用户退出:" + userModel.getId());
			}
		}
		// 消毁session
		request.getSession().invalidate();
		return "redirect:/manage";
	}
}
